package com.bdqn.t350.vue.common.filter;

import com.bdqn.t350.vue.bean.LoginUser;
import com.bdqn.t350.vue.utils.JwtTokenUtil;
import com.bdqn.t350.vue.utils.RedisUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * token jwt认证过滤器
 * 该过滤器需要在SecurityConfig中配置过滤器的执行顺序
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    //@Resource
    //RedisUtil redisUtil;

    @Resource
    RedisTemplate redisTemplate;


    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain)
            throws ServletException, IOException {
        //从请求头中获取token
        String token = httpServletRequest.getHeader("token");
        if (token == null) {
            //放行此次请求
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        //验证token
        if (!JwtTokenUtil.checkSign(token)) {
            throw new RuntimeException("token非法...");
        }
        //解析token
        String userId = JwtTokenUtil.getUserId(token);
        if (userId == null) {
            throw new RuntimeException("token非法");
        }
        //从redis中获取用户信息
        String redisKey = "loginUserId:" + userId;
        LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get(redisKey);
        if (Objects.isNull(loginUser)) {
            throw new RuntimeException("用户未登录");
        }
        //存入SecurityContextHolder
        //获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //最后处理完成之后执行放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}